const express = require("express");
const app = express();
// 启动端口号
const port = 3000;

// body-parser
const bodyParser = require("body-parser");

// 连接数据库
const connection = require("./databases/index");

// 生成和解析token值
const jwt = require("jsonwebtoken");
const expressJwt = require("express-jwt");

// cors 解决跨域
var cors = require("cors");
app.use(cors());
app.use(bodyParser.json());

// 服务器启动
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

app.get("/", (req, res) => {
  // res.send("Hello World!");
  console.log("Express创建的后端接口连接成功!!");
  res.send("Express创建的后端接口连接成功");
});

app.get("/inspection", (req, res) => {
  // res.send("Hello World!");
  // console.log("连接mysql成功");
  const sql = "select * from inspection limit 0,20";
  connection.query(sql, (err, info) => {
    if (err) {
      console.log(err);
      res.send("query error");
    } else {
      // 将 MySQL 查询结果作为路由返回值
      console.log(req.path, "获取inspection数据");
      let data = {
        code: 200,
        message: "success",
        info,
      };
      res.send(data);
    }
  });
});

app.post("/inspectionData-paging", (req, res) => {
  let currentPage = req.body.currentPage;
  let pageSize = req.body.pageSize;
  let count = "select count(*) as count from inspection";
  const sql = "select * from inspection limit ?,?";
  connection.query(count, (err, info) => {
    if (err) {
      console.log(err);
      res.send("query error");
    } else {
      let len = info[0].count;
      let offset = (currentPage - 1) * pageSize;
      let data = [offset, pageSize];
      console.log(req.body, data);
      connection.query(sql, data, (err, info) => {
        if (err) {
          console.log(err);
          res.send("query error");
        } else {
          let data = {
            code: 200,
            message: "success",
            count: len,
            info,
          };
          res.send(data);
        }
      });
    }
  });
});

app.get("/test", (req, res) => {
  res.send("User created!");
  // console.log(res);
});

app.put("/users/:id", (req, res) => {
  res.send(`User ${req.params.id} updated!`);
});

app.delete("/users/:id", (req, res) => {
  res.send(`User ${req.params.id} deleted!`);
});

app.all("/secret", function (req, res, next) {
  console.log("Accessing the secret section ...");
  next(); // pass control to the next handler
});

app.use((req, res, next) => {
  console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`);
  next();
});

app.post("/first/:id", (req, res) => {
  let { method, query, body, params, headers } = req;
  let data = { method, query, body, params, headers };
  console.log(data);
  res.status(200).send(data);
});

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send("服务器出错了!");
});

app.use((req, res, next) => {
  res.status(404).send("Not Found");
});

// 测试分组路由
const testRouter = require("./routes/test");
app.use("/test", testRouter);
